package plgnet

import (
	"dgo/MyProj/PrjHttpClt"
	"dgo/plg/plgbase"
	"flag"
	"fmt"
	"gitee.com/ymofen/gobase/golog"
	"gitee.com/ymofen/supervalue"
	"net/url"
	"strings"
)

var (
	CmdAddr   string
	json_cmd  string
	json_file string
)

func CmdPrepare4Plugs() {
	flag.StringVar(&CmdAddr, "cmd-addr", "", "[IP:PORT]")
	flag.StringVar(&json_cmd, "json-cmd", "", `JSON URLEncode {"id":"", "conf":{"type":""}`)
	flag.StringVar(&json_file, "json-file", "", "")
}

func CheckStartupPlgHttpService(caption string) bool {
	if len(CmdAddr) == 0 {
		return false
	}
	templ := `
  {
    "id": "PlgCtrl",
    "type": "net.http.plgctrl",
    "conf": {
      "addr": "%s",
      "caption": "%s"
    }
  }
`

	str := fmt.Sprintf(templ, CmdAddr, caption)
	json, err := wrapper.NewSVFromBuf([]byte(str))
	if err != nil {
		golog.Warnf("启动Plg控制插件异常:%s, \n%s", err.Error(), str)
		return false
	}
	_, _, err = plgbase.PlgCheckReloadFromJSON(json)
	if err != nil {
		golog.Warnf("启动Plg控制插件异常:%s, \n%s", err.Error(), str)
		return false
	}
	return true
}

func DoPostPluginConf2ApiSvr(json *wrapper.SuperValue) error {
	if len(CmdAddr) == 0 {
		return fmt.Errorf("cmd-addr is empty!")
	}
	http_addr := CmdAddr
	if http_addr[0] == ':' {
		http_addr = "http://127.0.0.1" + http_addr
	} else {
		if strings.Index(http_addr, "0.0.0.0") != -1 {
			http_addr = strings.ReplaceAll(http_addr, "0.0.0.0", "127.0.0.1")
		}
		if strings.Index(http_addr, "http") != 0 {
			http_addr = "http://" + http_addr
		}
	}
	if http_addr[len(http_addr)-1] == '/' {
		http_addr += "sys/cmd"
	} else {
		http_addr += "/sys/cmd"
	}

	golog.Warnf("cmd-addr:%s, raw:%s", http_addr, CmdAddr)

	{
		resp, err := PrjHttpClt.PostJsonEx(http_addr, json.AsJSONString(true))
		if err != nil {
			return err
		} else {
			msg := resp.StringByName("msg", "")
			if len(msg) > 0 {
				return fmt.Errorf("jsoncmd http resp msg :%s, errcode:%d", msg, resp.IntByName("errcode", 0))
			}
		}
	}
	return nil
}

func DoJSONCmd() bool {
	if len(json_cmd) > 0 {
		str, err := url.PathUnescape(json_cmd)
		if err != nil {
			golog.Warnf("jsoncmd PathUnescape err:%s", err.Error())
			return true
		}

		json, err := wrapper.NewSVFromBuf([]byte(str))
		if err != nil {
			golog.Warnf("jsoncmd json parse err:%s", err.Error())
			return true
		}

		{
			err := DoPostPluginConf2ApiSvr(json)
			if err != nil {
				golog.Warnf("jsoncmd err %s", err.Error())
			}
		}
		return true
	}
	return false
}

func DoJsonFile() bool {
	if len(json_file) > 0 {
		json, err := wrapper.NewSVFromFile(json_file)
		if err != nil {
			golog.Warnf("JSONFile(%s) parse err:%s", json_file, err.Error())
			return true
		}

		{
			err := DoPostPluginConf2ApiSvr(json)
			if err != nil {
				golog.Warnf("JSONFile reload err %s", err.Error())
			}
		}
		return true
	}
	return false
}
